package com.geh.learn.cipher;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class AesTest {

    /**
     * AES加密
     *
     * @param aesKey 密钥
     * @param text 明文
     * @return 密文
     */
    public static String encryptAes(String aesKey, String text) {
        try {
            byte[] key = aesKey.getBytes(Charsets.UTF_8);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encryptBytes = cipher.doFinal(text.getBytes(Charsets.UTF_8));
            // Base64一下，解密的时候先解码
            return BaseEncoding.base64().encode(encryptBytes);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * AES解密
     *
     * @param aesKey 密钥
     * @param text 密文
     * @return 明文
     */
    public static String decryptAes(String aesKey, String text) {
        try {
            byte[] key = aesKey.getBytes(Charsets.UTF_8);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptBytes = cipher.doFinal(BaseEncoding.base64().decode(text));
            return new String(decryptBytes, Charsets.UTF_8);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String original = "Hello World!";
        String password = "Passw0rd";
        System.out.println("original = " + original);
        System.out.println("password = " + password);

        // md5一下，正好32位
        String passwordMd5 =  Hashing.md5().hashString(password, Charsets.UTF_8).toString();

        String encyptedText = encryptAes(passwordMd5, original);
        System.out.println("encryptAes = " + encyptedText);
        System.out.println("decryptAes = " + decryptAes(passwordMd5, encyptedText));

//        String original = "Hello World!";
//        String password = "Passw0rd";
//        String passwordMd5 =  Hashing.md5().hashString(password, Charsets.UTF_8).toString();
//
//        String encrypted = SecureUtil.aes(passwordMd5.getBytes("UTF-8")).encryptBase64(original);
//
//        System.out.println(encrypted);
//
//        System.out.println(SecureUtil.aes(passwordMd5.getBytes("UTF-8")).decryptStr(Base64.decode(encrypted), Charset.forName("UTF-8")));
    }

}
